package admin

import (
	"context"
	"strconv"
	"strings"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/crypto/bcrypt"
)

type UserAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAddLogic) UserAdd(req *types.AddUser) error {
	if req.PWD != req.PWD2 {
		return errors.Wrapf(xerr.NewErrCodeMsg(500001, "密码不相等"), "pwd:%s,pwd1:%s", req.PWD, req.PWD2)
	}

	rb := l.svcCtx.Models.User.RowBuilder().Where("name = ?", req.Name)
	user, err := l.svcCtx.Models.User.FindOneByQuery(l.ctx, rb)
	if err != nil && err != model.ErrNotFound {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "查找用户数据库出错")
	}
	if user != nil {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_ALREADY_EXIST), "用户已存在")
	}

	pwd, _ := bcrypt.GenerateFromPassword([]byte(req.PWD), bcrypt.MinCost)

	roleIdArry := make([]string, 0)
	for _, roleId := range req.Role {
		roleIdArry = append(roleIdArry, strconv.Itoa(roleId))
	}
	roleIdStr := strings.Join(roleIdArry, ",")

	u := &model.AdminUser{
		Nickname: req.Name,
		RealName: req.RealName,
		Password: string(pwd),
		Email:    "",
		Name:     req.Name,
		Avatar:   req.Avatar,
		Roles:    roleIdStr,
	}

	_, err = l.svcCtx.Models.User.Insert(l.ctx, nil, u)
	if err != nil {
		return errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "插入用户数据库出错")
	}

	return err
}
